package lg.minecraft.plugin.pokemonmenu.manager;

import lg.minecraft.plugin.pokemonmenu.PokemonPlayer;
import lg.minecraft.plugin.pokemonmenu.util.LRUCacheMap;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.Map;
import java.util.UUID;

/**
 * @author langle__
 * @version 1.0
 */
public class PokemonPlayerManger {

    public static final PokemonPlayerManger INSTANCE = new PokemonPlayerManger();

    private final Map<UUID, PokemonPlayer> pokemonPlayerMap = new LRUCacheMap<>(100);

    private PokemonPlayerManger() {}

    public PokemonPlayer getPokemonPlayer(UUID uuid) {
        PokemonPlayer pokemonPlayer = pokemonPlayerMap.get(uuid);
        if (pokemonPlayer == null) {
            Player player = Bukkit.getPlayer(uuid);
            if (player != null && player.isOnline()) {
                pokemonPlayer = new PokemonPlayer(player);
            } else {
                pokemonPlayer = new PokemonPlayer(uuid);
            }
            pokemonPlayerMap.put(uuid, pokemonPlayer);
        }
        // 如果不存在，创建新的实例并放入缓存
        return pokemonPlayer;
    }

    public PokemonPlayer getPokemonPlayer(Player player) {
        return getPokemonPlayer(player.getUniqueId());
    }

    /**
     * 判断指定的玩家是否已经存在对应的 PokemonPlayer 实例。
     *
     * @param uuid 玩家的 UUID
     * @return 如果存在返回 true，否则返回 false
     */
    public boolean containsPokemonPlayer(UUID uuid) {
        return pokemonPlayerMap.containsKey(uuid);
    }

    /**
     * 手动添加或更新一个 PokemonPlayer 实例到缓存中。
     *
     * @param uuid 玩家的 UUID
     * @param pokemonPlayer 要添加的 PokemonPlayer 实例
     */
    public void addPokemonPlayer(UUID uuid, PokemonPlayer pokemonPlayer) {
        pokemonPlayerMap.put(uuid, pokemonPlayer);
    }

    /**
     * 从缓存中移除指定玩家的 PokemonPlayer 实例。
     *
     * @param uuid 玩家的 UUID
     */
    public void removePokemonPlayer(UUID uuid) {
        pokemonPlayerMap.remove(uuid);
    }

    /**
     * 获取当前缓存大小（用于监控）
     */
    public int getCurrentCacheSize() {
        return pokemonPlayerMap.size();
    }

    /**
     * 清空缓存（服务器关闭时调用）
     */
    public void clearCache() {
        pokemonPlayerMap.clear();
    }

}
